<!-- APP管理>广告发布 -->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      @submit.native.prevent
    >
      <el-form-item label="设施名" prop="facilitiesName">
        <el-input
          v-model="queryParams.facilitiesName"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button
            size="mini"
            circle
            icon="el-icon-refresh"
            @click="handleQuery"
          />
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          :content="showSearch ? '隐藏搜索' : '显示搜索'"
          placement="top"
        >
          <el-button
            size="mini"
            circle
            icon="el-icon-search"
            @click="showSearch = !showSearch"
          />
        </el-tooltip>
      </div>
    </el-row>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="50"
        align="center"
      />
      <el-table-column
        label="设施图标"
        align="center"
        prop="facilitiesIcon"
      >
        <template slot-scope="scope">
          <div>
            <img class="ad-img" :src="scope.row.facilitiesIcon" alt="" mode="widthFix"
                 style="width: 100px;height: 100px"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="设施名"
        align="center"
        prop="facilitiesName"
        :show-overflow-tooltip="true"
      />
<!--      <el-table-column-->
<!--        label="排序"-->
<!--        align="center"-->
<!--        prop="sort"-->
<!--        :show-overflow-tooltip="true"-->
<!--      >-->
<!--      </el-table-column>-->
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        :show-overflow-tooltip="true"
      />
<!--      <el-table-column-->
<!--        label="创建时间"-->
<!--        align="center"-->
<!--        prop="createTime"-->
<!--        :show-overflow-tooltip="true"-->
<!--      >-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column
        label="操作"
        align="center"
        width="350"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设施图标" prop="facilitiesIcon">
          <el-upload
            style="margin-top: 10px"
            class="image-uploader"
            :headers="headers"
            action="/api/common/upload"
            :show-file-list="false"
            accept=".jpg,.png"
            :on-success="onSuccess"
            :on-remove="onRemove"
          >
            <img v-if="form.facilitiesIcon" :src="form.facilitiesIcon" class="image"/>
            <i v-else class="el-icon-plus image-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb，长宽比例为 1:1
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="设施名" prop="facilitiesName">
          <el-input v-model="form.facilitiesName" placeholder="" show-word-limit maxlength="10" />
        </el-form-item>

        <el-form-item label="设施类型" prop="facilitiesType">
          <el-select v-model="form.facilitiesType" placeholder="请选择">
            <el-option
              v-for="item in dict.type.facilities_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="排序" prop="sort">-->
<!--          <el-input-number-->
<!--            v-model="form.sort"-->
<!--            controls-position="right"-->
<!--            :min="0"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder=""
            show-word-limit
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {areaInfo, listArea} from "@/api/system/config";

import {
  addFacilities,
  deleteFacilities,
  getFacilitiesDetail,
  getFacilitiesList,
  updateFacilities
} from "@/api/base/facilities";

export default {
  dicts: ["ad_type", "ad_location",'facilities_type'],
  name: "serverFacilities",
  components: {},
  data() {
    return {
      headers: {
        Authorization: `Bearer   ` + getToken(),
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 选中行
      ids: [],
      // 总条数
      total: 0,
      // 参数表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        facilitiesName: "",//设施名称
      },
      currentPage: 1,
      pageSize: 10,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        facilitiesName: [
          {
            required: true,
            message: "请输入设施名",
            trigger: "blur",
          }
        ],
        facilitiesType: [
          {
            required: true,
            message: "请选择设施类型",
            trigger: "blur",
          }
        ],
      },
      // 图片文件
      adImageFile: undefined,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSelectionChange(val) {
      console.log('handleSelectionChange',val)
      this.ids = val.map((item) => item.facilitiesId);
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      getFacilitiesList(this.addDateRange(this.queryParams)).then(
        (response) => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form =
        {
          facilitiesId: "", //设施id
          facilitiesName: "", //设施名
          facilitiesIcon: "", //设施图标
          facilitiesType: null, //设施类型（1服务，2设施，3建筑，4卫浴，5餐厨，6娱乐）
          sort: 0, //排序
          remark: null,
        };
      this.adImageFile = undefined;

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 0;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设施";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改设施";
      getFacilitiesDetail(row.facilitiesId).then((res) => {
        this.form = res.data;
        this.open = true;
      });
    },
    // 日期范围
    onSuccess(response, file, fileList) {
      this.$set(this.form, "facilitiesIcon", response.url);
    },
    onRemove() {
      this.form.houseQrCode = "";
    },
    /** 提交按钮 */
    handleSubmit: function () {
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let form = {...this.form}
          if (this.form.facilitiesId) {
            updateFacilities(form).then((response) => {
              this.open = false;
              this.getList();
              this.$message({
                message: "修改成功",
                type: "success",
              });
            });
          } else {
            addFacilities(form).then((response) => {
              this.open = false;
              this.getList();
              this.$message({
                message: "新增成功",
                type: "success",
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const facilitiesIds = row.facilitiesId || this.ids;
      console.log("handleDelete", facilitiesIds)
      this.$confirm("是否确认删除选中的设施？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return deleteFacilities(facilitiesIds);
        })
        .then(() => {
          this.getList();
          this.$message({
            message: "删除成功",
            type: "success",
          });
        })
        .catch(function () {
        });
    },
    // 图片上传
    async beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.form.file = reader.result;
          this.adImageFile = file;
          this.updataShow = true;
          this.$forceUpdate();
        };
      }
      // 返回false则不会调用默认的上传行为
      return false;
    },
  },
};
</script>

<style lang="scss">
.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.image-uploader .el-upload:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.image {
  width: 178px;
  height: 178px;
  display: block;
}

.ad-img {
  width: 80rpx;
  height: 60rpx;
}
</style>
